<?php

namespace app\controller;

use app\model\User;
use app\service\UserPositionService;
use app\service\UserService;
use support\Response;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Db;

class UserController extends Base
{

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function index(): Response
    {
        $user = (new User())->find($this->user_id);
        return $this->success('ok', $user->toArray());
    }

    public function websocket(): Response
    {
        $info = [
            'user_id' => $this->user_id,
            'u_tm' => time() + 60 * 60 * 24
        ];
        $token = base64_encode(json_encode($info));
        $url = "ws://39.106.159.26:7273?token=$token";
        return $this->success('ok', ['url' => $url]);

    }


    public function change_money(): Response
    {
        // 启动事务
        Db::startTrans();
        try {
            $userService = new UserService();
            $money = $this->request->post('money', 0);
            $status = $this->request->post('status', 0);
            $type = $this->request->post('type', 0);
            $res = $userService->change_money($this->user_id, $money, $type, $status);
            if ($res['code'] == 0) {
                Db::rollBack();
            } else {
                Db::commit();
            }
            return json($res);
        } catch (\Exception $e) {
            Db::rollBack();
            return $this->fail("服务器异常");
        }

    }


    //获取地块
    public function get_position(): Response
    {
        $user_position_service = new UserPositionService();
        try {
            $res = $user_position_service->list($this->user_id);
            return $this->json($res);
        } catch (Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    //解锁地块
    public function unlock_position(): Response
    {
        try {
            $user_position_service = new UserPositionService();
            $position_x = $this->request->post('position_x', null);
            $position_y = $this->request->post('position_y', null);
            $res = $user_position_service->unlock_position($this->user_id,$position_x,$position_y);
            return $this->json($res);
        }catch (Exception $e){
            return $this->fail($e->getMessage());
        }
    }

    //角色投票
    public function vote(): Response
    {
        $user_position_service = new UserPositionService();
        try {
            $res = $user_position_service->list($this->user_id);
            return $this->json($res);
        } catch (Exception $e) {
            return $this->fail($e->getMessage());
        }


    }






}